<script setup>
import {onMounted, ref} from "vue";
import {useRoute, useRouter} from "vue-router";
import {UserLogin} from "@/utils/api/common.js";
import {ElMessage} from "element-plus";
import {useUserLoginStore} from "@/stores/AccountLogin.js";

const title = ref("");
const account = ref("");
const password = ref("");
const loginType = ref("");
const aPlaceholder = ref("");
const route = useRoute();
const router = useRouter();
const loginStore = useUserLoginStore();

const login = () => {
  if (account.value === '' || password.value === '') {
    ElMessage({
      message: '请填写账户与密码',
      type: 'error',
    })
    return;
  }
  UserLogin(account.value, password.value, loginType.value)
      .then(result => {
        if (result.code === 1) {
          if (loginType.value === "Enterprise_Login") {
            router.replace({name: 'enterprise-home'});
          } else if (loginType.value === "Graduate_Login") {
            router.replace({name: 'graduate-home'});
          } else if (loginType.value === "Admin_Login") {
            router.replace({name: 'admin-home'});
          }
          ElMessage({
            message: '欢迎登录系统',
            type: 'success',
          })
          loginStore.setAll(account.value, true, result.data)
        } else {
          ElMessage({
            message: result.message,
            type: 'error',
          })
        }
      }).catch(error => console.error(error.toString()))
}

onMounted(() => {
  if (route.name === "enterprise-login") {
    loginType.value = "Enterprise_Login";
    title.value = "企业登录";
    aPlaceholder.value = "企业编号";
  } else if (route.name === "graduate-login") {
    loginType.value = "Graduate_Login";
    title.value = "毕业生登录";
    aPlaceholder.value = "学 号";
  } else if (route.name === "admin-login") {
    loginType.value = "Admin_Login";
    title.value = "管理员登录";
    aPlaceholder.value = "账 号";
  } else {
    router.push({name: 'home', replace: true});
  }
});
</script>

<template>
  <div class="main">
    <h2> {{ title }} </h2>
    <el-form label-width="80px">
      <el-form-item label="账 号">
        <el-input type="text" v-model="account" :placeholder="aPlaceholder"/>
      </el-form-item>
      <el-form-item label="密 码">
        <el-input type="password" v-model="password" placeholder="密 码"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="login">登 录</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="router.push({name:'home', replace:true})">返 回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
.main {
  margin: 100px;
}

h2 {
  padding-left: 40px;
}

.el-form {
  margin-top: 20px;
  min-width: 500px;
  width: 500px;
}

.el-form-item {
  width: 90%;
}

.el-button {
  width: 100%;
}

</style>